package student;

import java.sql.*;
import java.util.HashMap;

public class Connectmysql {
    private String url;
    private String username;
    private String password;
    private String driver;
    private Connection connection;
    private Statement statement;
    private HashMap<String, PreparedStatement> preparedStatementList = new HashMap<>();
    private boolean autoCommit = true; // 默认自动提交

    public Connectmysql(String url, String username, String password, String driver) {
        this.url = url;
        this.username = username;
        this.password = password;
        this.driver = driver;
    }

    // 设置是否自动提交事务
    public void setAutoCommit(boolean autoCommit) throws SQLException {
        if (connection != null) {
            this.autoCommit = autoCommit;
            connection.setAutoCommit(autoCommit);
        }
    }

    public boolean open() throws ClassNotFoundException {
        return initConnection();
    }

    private boolean initConnection() throws ClassNotFoundException {
        Class.forName(driver);
        try {
            connection = DriverManager.getConnection(this.url, this.username, this.password);
            connection.setAutoCommit(autoCommit); // 设置自动提交模式
            statement = connection.createStatement();
            return true;
        } catch (SQLException e) {
            System.err.println("数据库连接期间出现异常");
            e.printStackTrace();
            return false;
        }
    }

    // 获取连接对象
    public Connection getConnection() {
        return connection;
    }

    // 开启事务（设置手动提交）
    public void beginTransaction() throws SQLException {
        if (connection != null) {
            autoCommit = false;
            connection.setAutoCommit(false);
        }
    }

    // 提交事务
    public void commit() throws SQLException {
        if (connection != null && !autoCommit) {
            connection.commit();
            autoCommit = true;
            connection.setAutoCommit(true);
        }
    }

    // 回滚事务
    public void rollback() throws SQLException {
        if (connection != null && !autoCommit) {
            connection.rollback();
            autoCommit = true;
            connection.setAutoCommit(true);
        }
    }

    public ResultSet executeSql(String sql, Object[] values) throws SQLException {
        PreparedStatement statement = null;
        if (preparedStatementList.containsKey(sql)) {
            statement = preparedStatementList.get(sql);
        } else {
            statement = connection.prepareStatement(sql);
            preparedStatementList.put(sql, statement);
        }

        statement.clearParameters();
        int paramIndex = 1;
        for (Object val : values) {
            statement.setObject(paramIndex, val);
            paramIndex++;
        }

        return statement.executeQuery();
    }

    public ResultSet executeSqlSearch(String sql, Object[] values) throws SQLException {
        PreparedStatement statement = null;
        if (preparedStatementList.containsKey(sql)) {
            statement = preparedStatementList.get(sql);
        } else {
            statement = connection.prepareStatement(sql);
            preparedStatementList.put(sql, statement);
        }

        statement.clearParameters();
        int paramIndex = 1;
        for (Object val : values) {
            statement.setObject(paramIndex, "%" + val + "%");
            paramIndex++;
        }

        return statement.executeQuery();
    }

    public int executeSqlUpdate(String sql, Object[] values) throws SQLException {
        PreparedStatement statement = null;
        try {
            if (preparedStatementList.containsKey(sql)) {
                statement = preparedStatementList.get(sql);
            } else {
                statement = connection.prepareStatement(sql);
                preparedStatementList.put(sql, statement);
            }

            statement.clearParameters();
            int paramIndex = 1;
            for (Object val : values) {
                statement.setObject(paramIndex, val);
                paramIndex++;
            }

            return statement.executeUpdate();
        } catch (SQLException e) {
            System.err.println("执行更新期间出现异常:" + sql + "@" + values);
            throw e; // 重新抛出异常，让调用者处理
        }
    }

    public boolean close() {
        try {
            // 关闭所有预编译语句
            for (PreparedStatement stmt : preparedStatementList.values()) {
                if (stmt != null && !stmt.isClosed()) {
                    stmt.close();
                }
            }
            preparedStatementList.clear();

            if (statement != null && !statement.isClosed()) {
                statement.close();
            }
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
            return true;
        } catch (SQLException e) {
            System.err.println("数据库关闭期间出现异常");
            e.printStackTrace();
            return false;
        }
    }
}